package test;

import javax.jms.Connection;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;

public class MsgConsumer implements MessageListener {

	private String queueName = "org.lsda.jobs";

	private String url = "tcp://localhost:61616";

	private String userName = "lsda";

	private String password = "admin";

	private int msgCnt = 0;
	
	private Session session = null;

	public MsgConsumer() {
	}

	public void consumeMsg() {
		Connection connection = null;
		try {
			ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(
					userName, password, url);
			connection = connectionFactory.createConnection();
			connection.start();

			session = connection.createSession(true,
					Session.AUTO_ACKNOWLEDGE);

			Destination destination = session.createQueue(queueName);

			MessageConsumer consumer = session.createConsumer(destination);
			consumer.setMessageListener(this);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	@Override
	public void onMessage(Message msg) {
		// TODO Auto-generated method stub
		msgCnt++;
		if (msg instanceof TextMessage) {
			TextMessage textMsg = (TextMessage) msg;

			try {
				System.out.println("rev:" + msgCnt + " " + textMsg.getText());
				session.commit();
			} catch (JMSException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	public static void main(String args[]) {
		MsgConsumer consumer = new MsgConsumer();
		
		consumer.consumeMsg();
	}

}
